/*
  Losu Copyright Notice
  --------------------
    Losu is an open source programming language project under the MIT license
  that can be used for both academic and commercial purposes. There are no
  fees, no royalties, and no GNU-like "copyright" restrictions. Losu qualifies
  as open source software. However, Losu is not public property, and founder
  'chen-chaochen' retains its copyright.

    Losu has been registered with the National Copyright Administration of the
  People's Republic of China, and adopts the MIT license as the copyright
  licensing contract under which the right holder conditionally licenses its
  reproduction, distribution, and modification rights to an unspecified public.

    If you use Losu, please follow the public MIT agreement or choose to enter
  into a dedicated license agreement with us.

  The MIT LICENSE is as follows
  --------------------
  Copyright  2020 - now  chen-chaochen

    Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the “Software”), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

/*
    This document is part of the Losu Community OSPP - 2024 subject results
  contributed by Dongqiao Huang @ NEUQ, following MIT LICENSE Contributed to
  the Losu Community.

  The MIT LICENSE is as follows
  --------------------
  Copyright 2024 Dongqiao Huang

    Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the “Software”), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
 */

/* include headfile */
#include "losuc.h"

/* static segment */

/* function for object */
static void __losuIrEncodeHead (FILE *f, _l_bool isC);
static void __losuIrEncodeFunc (_inlineScode *fs, FILE *f, _l_bool isC);
static void __losuIrEncodeConst (_inlineScode *fs, FILE *f, _l_bool isC);
static void __losuIrEncodeLine (_inlineScode *fs, FILE *f, _l_bool isC);
static void __losuIrEncodeLcvar (_inlineScode *fs, FILE *f, _l_bool isC);
static void __losuIrEncodeIns (_inlineScode *fs, FILE *f, _l_bool isC);
static void __losuIrEncodeString (_inlineString *s, FILE *f, _l_bool isC);
static void __losuIrEncodeSizet (_l_size_t n, FILE *f, _l_bool isC);
static void __losuIrEncodeInt32 (int32_t n, FILE *f, _l_bool isC);

/* IO function */
static void __losuIrEncodeByte (uint8_t c, FILE *f, _l_bool isC);
static void __losuIrEncodeBlock (void *p, size_t len, FILE *f, _l_bool isC);
static void __losuIrEncodeVector (void *p, size_t n, size_t s, FILE *f,
                                  _l_bool isC);

/* function segment */
/*  Encode functions */
LosuExtern void
__losu_bytecode_encode (_inlineScode *main, FILE *f, _l_bool isC)
{
  if (isC)
    {
      fputc ('{', f);
      fputc ('\n', f);
      fputc (' ', f);
      fputc (' ', f);
    }
  __losuIrEncodeHead (f, isC);
  __losuIrEncodeFunc (main, f, isC);
  if (isC)
    {
      fputc ('\n', f);
      fputc ('}', f);
      fputc (';', f);
      fputc ('\n', f);
    }
}

static void
__losuIrEncodeHead (FILE *f, _l_bool isC)
{
  int32_t i = 1;
  /* magic */
  __losuIrEncodeByte (0, f, isC);
  /* Endianness */
  __losuIrEncodeByte ((*(uint8_t *)(&i)), f, isC);
  /* Version */
  __losuIrEncodeSizet (LosuVersionNum, f, isC);
  /* Vm-bitsize */
  __losuIrEncodeByte (sizeof (vmInstruction), f, isC);
}

static void
__losuIrEncodeFunc (_inlineScode *fs, FILE *f, _l_bool isC)
{
  __losuIrEncodeString (fs->src, f, isC);
  __losuIrEncodeInt32 (fs->defedline, f, isC);
  __losuIrEncodeInt32 (fs->narg, f, isC);
  __losuIrEncodeByte (fs->isVarg, f, isC);
  __losuIrEncodeInt32 (fs->maxstacksize, f, isC);

  __losuIrEncodeLcvar (fs, f, isC);
  __losuIrEncodeLine (fs, f, isC);
  __losuIrEncodeConst (fs, f, isC);

  __losuIrEncodeIns (fs, f, isC);
}

static void
__losuIrEncodeConst (_inlineScode *fs, FILE *f, _l_bool isC)
{
  /* encode lcstr */
  __losuIrEncodeInt32 (fs->nlcstr, f, isC);
  for (int32_t i = 0; i < fs->nlcstr; i++)
    __losuIrEncodeString (fs->lcstr[i], f, isC);

  /* encode lcnum */
  __losuIrEncodeInt32 (fs->nlcnum, f, isC);
  __losuIrEncodeVector (fs->lcnum, fs->nlcnum, sizeof (*fs->lcnum), f, isC);

  /* encode lcscode */
  __losuIrEncodeInt32 (fs->nlcscode, f, isC);
  for (int32_t i = 0; i < fs->nlcscode; i++)
    __losuIrEncodeFunc (fs->lcscode[i], f, isC);
}

static void
__losuIrEncodeLine (_inlineScode *fs, FILE *f, _l_bool isC)
{
  __losuIrEncodeInt32 (fs->nlineinfo, f, isC);
  __losuIrEncodeVector (fs->lineinfo, fs->nlineinfo, sizeof (*fs->lineinfo), f,
                        isC);
}

static void
__losuIrEncodeLcvar (_inlineScode *fs, FILE *f, _l_bool isC)
{
  __losuIrEncodeInt32 (fs->nlocalvar, f, isC);
  for (int32_t i = 0; i < fs->nlocalvar; i++)
    {
      __losuIrEncodeString (fs->localvar[i].name, f, isC);
      __losuIrEncodeInt32 (fs->localvar[i].startpc, f, isC);
      __losuIrEncodeInt32 (fs->localvar[i].endpc, f, isC);
    }
}

static void
__losuIrEncodeIns (_inlineScode *fs, FILE *f, _l_bool isC)
{
  __losuIrEncodeInt32 (fs->ncode, f, isC);
  __losuIrEncodeVector (fs->code, fs->ncode, sizeof (*fs->code), f, isC);
}

static void
__losuIrEncodeString (_inlineString *s, FILE *f, _l_bool isC)
{
  if (s == NULL)
    __losuIrEncodeSizet (0, f, isC);
  else
    {
      size_t len = s->len + 1;
      __losuIrEncodeSizet (len, f, isC);
      __losuIrEncodeBlock (s->str, len, f, isC);
    }
}
static void
__losuIrEncodeSizet (_l_size_t n, FILE *f, _l_bool isC)
{
  __losuIrEncodeBlock (&n, sizeof (_l_size_t), f, isC);
}
static void
__losuIrEncodeInt32 (int32_t n, FILE *f, _l_bool isC)
{
  __losuIrEncodeBlock (&n, sizeof (n), f, isC);
}

static void
__losuIrEncodeByte (uint8_t c, FILE *f, _l_bool isC)
{
  static int8_t i = 0;
  if (isC)
    {
      fprintf (f, "0x%.2x, ", (int32_t)c);
      i++;
      if (i == 13)
        {
          fputc ('\n', f);
          fputc (' ', f);
          fputc (' ', f);

          i = 0;
        }
    }
  else
    fputc (c, f);
}
static void
__losuIrEncodeBlock (void *p, size_t len, FILE *f, _l_bool isC)
{
  if (isC)
    {
      for (size_t i = 0; i < len; i++)
        __losuIrEncodeByte (((uint8_t *)p)[i], f, isC);
    }
  else
    fwrite (p, len, 1, f);
}
static void
__losuIrEncodeVector (void *p, size_t n, size_t s, FILE *f, _l_bool isC)
{
  if (isC)
    {
      for (size_t i = 0; i < n; i++)
        __losuIrEncodeBlock (((uint8_t *)p) + i * s, s, f, isC);
    }
  else
    fwrite (p, n, s, f);
}
